﻿using LayuiMvc.DataModel.Identity;
using LayuiMvc.Logic.Identity;
using LayuiMvcUtil.Exception;
using LayuiMvcUtil.Result;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace LayuiMvc.WebUI.Areas.Admin.Controllers
{
    public class AccountManageController : Controller
    {
        #region 管理器
        /// <summary>
        /// 从Owin上下文中获取用户管理器
        /// </summary>
        private IdentityUserManager UserManager
        {
            get { return HttpContext.GetOwinContext().GetUserManager<IdentityUserManager>(); }
        }
        /// <summary>
        /// 登录管理器
        /// </summary>
        private IdentitySignInManager SignInManager
        {
            get { return HttpContext.GetOwinContext().Get<IdentitySignInManager>(); }
        }

        /// <summary>
        /// 授权管理器
        /// </summary>
        private IAuthenticationManager AuthenicationManager
        {
            get { return HttpContext.GetOwinContext().Authentication; }
        }
        #endregion

        #region 用户管理==用户登陆

        /// <summary>
        /// 返回登录视图页
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userLoginModel">用户登录业务模型类</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Login(UserLoginModel userLoginModel)
        {
            DataResult<string> rtnResult = new DataResult<string>();
            try
            {
                await SignInManager.UserLoginAsync(userLoginModel);
            }
            catch (CustomException exception)
            {
                rtnResult.code = 1;
                rtnResult.msg = exception.Message;
            }
            return Json(rtnResult);
        }
        #endregion

        #region 用户管理==用户销户
        public ActionResult SignOut()
        {
            AuthenicationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return RedirectToAction("Login");
        }
        #endregion

        #region 账户管理==加载个人信息
        /// <summary>
        /// 加载当前登录用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<ActionResult> LoadUserMsg()
        {
            DataResult<UserMsgModel> rtnResult = new DataResult<UserMsgModel>();
            UserMsgModel userMsgModel = new UserMsgModel();

            userMsgModel.IsLogin = HttpContext.User.Identity.IsAuthenticated;
            userMsgModel.UserId = HttpContext.User.Identity.GetUserId<int>();

            if (userMsgModel.IsLogin)
            {
                userMsgModel = await UserManager.UpdateUserMsgInit(userMsgModel.UserId);
                userMsgModel.IsLogin = true;
            }

            rtnResult.data = userMsgModel;

            return Json(rtnResult);
        }
        #endregion

        #region 用户管理==用户注册
        /// <summary>
        /// 用户注册视图跳转
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 用户注册提交
        /// </summary>
        /// <param name="registerModel">要注册的用户信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> Register(UserRegisterModel registerModel)
        {
            DataResult<string> rtnResult = new DataResult<string>();
            try
            {
                await UserManager.UserRegisterAsync(registerModel);
            }
            catch (CustomException exception)
            {
                rtnResult.code = 1;
                rtnResult.msg = exception.Message;
            }

            return Json(rtnResult);
        }
        #endregion

        #region 用户管理==修改个人信息

        public ActionResult UpdateUserMsg()
        {
            return View();
        }
        /// <summary>
        /// 用户个人信息修改初始化
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> UpdataUserMsgInit()
        {
            DataResult<UserMsgModel> rtnResult = new DataResult<UserMsgModel>();
            //获取当前登录用户的UserId
            int userId = HttpContext.User.Identity.GetUserId<int>();
            UserMsgModel userMsgModel = await UserManager.UpdateUserMsgInit(userId);
            rtnResult.data = userMsgModel;
            return Json(rtnResult);
        }

        public async Task<ActionResult> UpdateUserHeadImg()
        {
            int userId = HttpContext.User.Identity.GetUserId<int>();

            DataResult<string> rtnResult = new DataResult<string>();
            HttpPostedFileBase file = Request.Files[0];
            if (file!=null&&!string.IsNullOrEmpty(file.FileName))
            {
                var saveFileName = Guid.NewGuid().ToString("N") + "_" + file.FileName;

                file.SaveAs(Path.Combine(Server.MapPath("~/UpdateFile/HeadImg"), saveFileName));
                await UserManager.UpdateUserHeadImgAsync(userId, $"/UploadFile/HeadImg/{saveFileName}");

                rtnResult.data = $"/UploadFile/HeadImg/{saveFileName}";

            }
            return Json(rtnResult);
         }
        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <param name="userMsgModel">个人</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> UpdateUserMsg(UserMsgModel userMsgModel)
        {
            DataResult<string> rtnResult = new DataResult<string>();
            try
            {
                int userId = HttpContext.User.Identity.GetUserId<int>();
                userMsgModel.UserId = userId;
                await UserManager.UpdateUserMsgAsync(userMsgModel);
            }
            catch (CustomException exception)
            {
                rtnResult.code = 1;
                rtnResult.msg = exception.Message;
            }
            return Json(rtnResult);
        }
        #endregion
    }
}